"""
对httprunner进行二次封装
"""
from common.ConfRead import ConfigReader
from httprunner import HttpRunner,Step,RunTestCase,RunRequest,Config
from business.login_test import TestCaseLogin as Login
base_path = ConfigReader('config.ini').get_option('dev_base_url')       # 整个项目的url地址在这里控制
# 基础方法封装
class Perform(HttpRunner):
    config = Config("test start..").\
        base_url(base_path).\
        verify(False)
    teststeps = [
        Step(
            RunTestCase("登录").\
                call(Login).\
                export(*['token',])
        ),
    ]

# 重置登录权限
"""
比如一个电商网站，会有管理员、游客、商家等等不同的权限
"""
def reset_token(token=Login):
    # 先去清空这个列表里的登录
    Perform.teststeps.clear()
    # 再去添加新的登录权限
    Perform.teststeps.append(
        Step(
            RunTestCase("登录").
                call(token).\
                export(*['token',])
        )
    )
# 所有请求头，都是固定的，所以这里就写死了
headers = {'Authori-zation': 'Bearer ${token}'}
# 发送请求的方法
def send_requests(name,method,path,requests_body=None,headers=headers):
    if method == 'get':
        return RunRequest(name).\
                get(path).\
                with_headers(**headers).\
                extract().\
                with_jmespath("body",'res_data')
    elif method =='post':
        return RunRequest(name).\
                post(path).\
                with_json(requests_body).\
                with_headers(**headers). \
                extract(). \
                with_jmespath("body", 'res_data')
    elif method == 'put':
        return RunRequest(name).\
                put(path).\
                with_headers(**headers). \
                extract(). \
                with_jmespath("body", 'res_data')
    elif method == 'delete':
        return RunRequest(name).\
                delete(path).\
                with_headers(**headers).\
                extract().\
                with_jmespath("body", 'res_data')

# 为所有的请求，增加Step
def obj_step(obj):
    return Step(
        obj
    )

# 执行接口测试
def get_last_response(obj:list):
    # 把所有的请求步骤，加到列表里面
    Perform.teststeps.extend(obj)
    # 实例化对象
    perform = Perform()
    # 执行测试
    perform.test_start()
    # 收集所有的响应结果
    res = perform.with_export(['token','res_data']).get_export_variables()
    return res      # {"token":"asdasdas","res_data":{"status":200,"msg":"succes"}}















